package com.lgmshare.component.widget.recyclerview;

import android.content.Context;
import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * RecyclerView的LinearLayoutManager布局的Item的bottom间距或right
 *
 * @author lim
 * @description: TODO
 * @email lgmshare@gmail.com
 * @datetime 2016/4/6 15:26
 */
public class LinearItemDecoration extends RecyclerView.ItemDecoration {

    private int mOrientation;
    private int mSpace;
    private int mHeaderCount;
    private boolean mIncludeEdge;

    public LinearItemDecoration(Context context, int orientation, int space) {
        this(context, orientation, space, 0);
    }

    public LinearItemDecoration(Context context, int orientation, int space, int headerCount) {
        this(context, orientation, space, headerCount, false);
    }

    public LinearItemDecoration(Context context, int orientation, int space, int headerCount, boolean includeEdge) {
        mOrientation = orientation;
        mIncludeEdge = includeEdge;
        mSpace = dipToPx(context, space);
        mHeaderCount = headerCount;
    }

    public void setOrientation(int orientation) {
        if (orientation != LinearLayoutManager.HORIZONTAL && orientation != LinearLayoutManager.VERTICAL) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        if (position < mHeaderCount) {
            return;
        }
        if (mOrientation == LinearLayoutManager.VERTICAL) {
            if (position == mHeaderCount) {
                outRect.top = mSpace;
            }
            outRect.bottom = mSpace;
            if (mIncludeEdge) {
                outRect.left = mSpace;
                outRect.right = mSpace;
            }
        } else {
            if (position == mHeaderCount) {
                outRect.left = mSpace;
            }
            outRect.right = mSpace;
            if (mIncludeEdge) {
                outRect.top = mSpace;
                outRect.bottom = mSpace;
            }
        }
    }

    private int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
